package com.senlingspace.payment.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 基于Jackson工具类
 *
 * @author lebronjames
 * @date 2024/07/22
 */
@Deprecated // 目前用不上
@Component
public class JsonMapperUtil {

    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 对象转String
     *
     * @param src
     * @param <T>
     * @return
     */
    public <T> String obj2String(T src) {
        if (null == src) {
            return null;
        }
        try {
            return src instanceof String ? (String) src : objectMapper.writeValueAsString(src);
        } catch (Exception e) {
            return null;
        }
    }

    public <T> T string2Obj(String src, TypeReference<T> typeReference) {
        if (null == src || null == typeReference) {
            return null;
        }
        try {
            return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference));
        } catch (Exception e) {
            return null;
        }
    }

}
